#include <iostream>
#include <unistd.h>
#include <pthread.h>

// 线程局部存储demo

// gval叫做线程的局部存储
__thread int gval = 1;

// 获取地址
std::string Attr(int &c)
{
    char addr[64];
    snprintf(addr, sizeof(addr), "%p", &c);
    return addr;
}

void *routine1(void *args)
{
    while (1)
    {
        std::cout << "我是Thread-1， gval：" << gval << "，[我来修改gval]："
                  << "&gval " << Attr(gval) << std::endl;
        gval++;
        sleep(1);
    }
    return nullptr;
}

void *routine2(void *args)
{
    std::string name = static_cast<char *>(args);
    while (1)
    {
        std::cout << "我是Thread-2， gval：" << gval << ", &gval "
                  << Attr(gval) << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    pthread_t tid1, tid2;
    pthread_create(&tid1, nullptr, routine1, (void *)"Thread-1");
    pthread_create(&tid2, nullptr, routine2, (void *)"Thread-2");

    sleep(5);

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);

    return 0;
}